package puzzle.sudoku.loader;

import puzzle.common.data.HatanException;
import puzzle.common.loader.AbstractLoader;
import puzzle.common.loader.Preprocessor;
import puzzle.sudoku.data.SudokuBoard;
import tomoto.assertion.AssertUtil;

public class SudokuLoader extends AbstractLoader<SudokuBoard> {

	public SudokuLoader() {
		super("\\s+");
	}

	@Override
	protected SudokuBoard process(Preprocessor pp) {
		int base = (int) Math.sqrt(pp.getWidth());
		int size = base * base;
		SudokuBoard b = new SudokuBoard(base);
		for (int y = 0; y < size; y++) {
			String[] fields = pp.getLines().get(y);
			for (int x = 0; x < size; x++) {
				int n = Integer.parseInt(fields[x]);
				if (n > 0) {
					try {
						b.setNumber(x, y, n);
					} catch (HatanException ex) {
						throw AssertUtil.fail();
					}
				}
			}
		}
		return b;
	}

}
